package com.liuqi.openai.data.document.source;

import com.liuqi.openai.data.document.DocumentSource;
import com.liuqi.openai.data.document.Metadata;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.liuqi.openai.data.document.Document.ABSOLUTE_DIRECTORY_PATH;
import static com.liuqi.openai.data.document.Document.FILE_NAME;
import static com.liuqi.openai.util.ValidationUtil.ensureNotNull;

/**
 * 文件类型的文档数据源
 *
 * @author liuqi
 * @date 2025/8/7
 **/
public class FileDocumentSource implements DocumentSource {

    private final Path path;

    private FileDocumentSource(Path path) {
        this.path = ensureNotNull(path, "path");
    }

    @Override
    public InputStream inputStream() throws IOException {
        return Files.newInputStream(path);
    }

    @Override
    public Metadata metadata() {
        return new Metadata()
                .add(FILE_NAME, path.getFileName())
                .add(ABSOLUTE_DIRECTORY_PATH, path.getParent().toAbsolutePath());
    }

    public static FileDocumentSource from(Path filePath) {
        return new FileDocumentSource(filePath);
    }

    public static FileDocumentSource from(String filePath) {
        return new FileDocumentSource(Paths.get(filePath));
    }

    public static FileDocumentSource from(URI fileUri) {
        return new FileDocumentSource(Paths.get(fileUri));
    }

    public static FileDocumentSource from(File file) {
        return new FileDocumentSource(file.toPath());
    }
}
